//
//  MLABaseSearchView.m
//  MagicLampApp
//
//  Created by Zheng on 2018/12/24.
//  Copyright © 2018 zheng.magic.lamp.app. All rights reserved.
//

#import "MLABaseSearchView.h"

@interface MLABaseSearchView () <UITextFieldDelegate>

@end

@implementation MLABaseSearchView {
    UIView *shadowView;
    UIImageView *searchImgv;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _canEdit = YES;
        shadowView = [[UIView alloc] init];
        shadowView.backgroundColor = [UIColor whiteColor];
        shadowView.layer.shadowColor = CX_GetColorHex(0x5C9EEB, 0.3).CGColor;
        shadowView.layer.shadowOffset = CGSizeMake(0, 1);
        shadowView.layer.shadowOpacity = 1;
        shadowView.layer.cornerRadius = 5;
        [self addSubview:shadowView];
        [shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.right.mas_equalTo(-15);
            make.top.mas_equalTo(20);
            make.bottom.mas_equalTo(-20);
        }];
        
        searchImgv = [[UIImageView alloc] init];
        searchImgv.image = [UIImage imageNamed:@"search_icon"];
        [shadowView addSubview:searchImgv];
        [searchImgv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.centerY.equalTo(self->shadowView);
            make.width.height.mas_equalTo(16);
        }];

        _textField = [[UITextField alloc] init];
        _textField.font = CX_GetNormalFont(12);
        _textField.placeholder = @"搜索";
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.delegate = self;
        [_textField addTarget:self action:@selector(textDidChanged:) forControlEvents:UIControlEventEditingChanged];
        [shadowView addSubview:_textField];
        [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self->searchImgv.mas_right).offset(20);
            make.right.mas_equalTo(-15);
            make.centerY.equalTo(self->searchImgv);
            make.height.offset(30);
        }];
    }
    return self;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (_shouldEditingBlock&&!_canEdit) {
        _shouldEditingBlock();
    }
    return _canEdit;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (_shouldDidClickSearch&&textField.text) {
        [textField resignFirstResponder];
        _shouldDidClickSearch();
    }
    return YES;
}

- (void)textDidChanged:(UITextField *)textField {
    _keyword = textField.text;
    if (_editChangeBlock) {
        _editChangeBlock(_keyword);
    }
}



@end
